(function(){
    angular.module('feibo.teacher.controller').controller('MiniClassOptController', MiniClassOptController);

    MiniClassOptController.$inject = ['$scope', '$stateParams', '$state', 'TeacherService', 'valiFrom', 'kvMap', 'CommonService'];

    function MiniClassOptController($scope, $stateParams, $state, TeacherService, valiFrom, kvMap, CommonService){
        var vm = this;
        vm.kvMap = {
            shiftTimeSlotType: CommonService.cloneMapping(kvMap.shiftTimeSlotType, ['vkMap'])
        };

        vm.data = {
            classId: $stateParams.id,
            isCheck: !$stateParams.edit,
            bigClassList: undefined,
            bigClass: {},
            tempSmallClass: {
                name: undefined,
                fb_shift_category_id: undefined
            },
            formData: {
                parent: {
                    name: undefined,
                    id: undefined,
                    wd_days: undefined,
                    wd_hours: undefined,
                    we_days: undefined,
                    we_hours: undefined,
                    monday_time: undefined,
                    tuesday_time: undefined,
                    wednesday_time: undefined,
                    thursday_time: undefined,
                    friday_time: undefined,
                    saturday_time: undefined,
                    sunday_time: undefined
                },
                bigClassId: undefined,
                name: undefined
            },
            weeks: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            timePoints: undefined,
            timeItemsData: undefined,
            bindTimeItemsData: []
        };

        vm.initData = function(){
            vm.initEvent();
            vm.creatTimePoint(6, 23);
            vm.fetchClassType();

            if(vm.data.classId){
                vm.getClassMiniType();
            }else {
                vm.data.isCheck = false;
            }
        };

        vm.initEvent = function(){
            var $bigClass = $('#big-class-dropdown');
            $bigClass.on('change', function(){
                var value = $bigClass.dropdown('get value');

                $scope.$apply(function(){
                    if(angular.isArray(value)){
                        vm.data.formData.bigClassId = value[0];
                    }else {
                        vm.data.formData.bigClassId = value;
                    }
                });
            });
        };

        vm.bigClassDropdownFinished = function(){
            var bigClassId;
            if(vm.data.classId){
                bigClassId = vm.data.tempSmallClass.fb_shift_category_id;
            }else {
                bigClassId = vm.data.bigClassList[0].id;
            }
            setTimeout(function(){
                $('#big-class-dropdown').dropdown('set selected', bigClassId);
            });
        };

        vm.editor = function(){
            vm.data.isCheck = false;
            $('.day div.ui.dropdown.disabled').removeClass('disabled');
        };

        // 生成时间点
        vm.creatTimePoint = function(start, end){
            var points = vm.data.timePoints = [];
            start = window.parseInt(start) || 0;
            end = window.parseInt(end) || 23;

            function fillZero(number){
                return number > 9 ? number : '0' + number;
            }

            for(var i = start; i <= end; i++){
                points.push(fillZero(i) + ':00');
                points.push(fillZero(i) + ':30');
            }
        };

        // 添加时间段
        vm.addTimePeriodBtn = function(event){
            var week = event.target.parentNode.parentNode;
            var $tpl = $('#shift-time-slot-tpl').children().clone(true);
            $tpl.find('.dropdown').dropdown();
            $tpl.appendTo(week);
        };

        // 删除时间段
        vm.deleteTimePeriodBtn = function(event){
            $(event.target.parentNode).remove();
        };

        vm.initTimePointDropdown = function(){
            $('#add-small-class-form .dropdown').dropdown();
        };

        vm.setDropdown = function(){
            vm.data.bindTimeItemsData.forEach(function(val){
                if(val.shift_time_slot){
                    val.shift_time_slot.forEach(function(v, i){
                        ['start_time', 'end_time', 'type'].forEach(function(key){
                            $('#' + val.day_of_week + i + key).dropdown('set selected', v[key]);
                        });
                    });
                }
            });
        };

        // 获取小类数据
        vm.getSmallClassData = function(){
            var smallClassData = vm.data.timeItemsData = [];
            $('#add-small-class-form .day').each(function(key, node){
                var temp = {
                    type: undefined,
                    start_time: undefined,
                    end_time: undefined
                };

                var $node = $(node);

                $node.find('section').each(function(k, n){
                    var $n = $(n);
                    Object.keys(temp).forEach(function(key){
                        temp[key] = Number($n.find('.' + key).dropdown('get value'));
                    });

                    temp.day_of_week = $node.attr('key');
                    for(var i = temp.start_time; i < temp.end_time; i++){
                        var item = {
                            day_of_week: temp.day_of_week,
                            type: temp.type,
                            time_slot: vm.data.timePoints[i]
                        };

                        smallClassData.push(item);
                    }
                });
            });
        };

        // 获取大类
        vm.fetchClassType = function(isFirst){
            var queryConfig = {
                funcName: 'fetchClassType',
                container: vm.data,
                propName: 'bigClassList',
                propChain: ['data', 'entries'],
                showLoadLayer: false
            };

            TeacherService.fetchClassType(queryConfig).then(function(returnedData){
                if(returnedData.success && returnedData.data && returnedData.data.entries){
                    vm.data.formData.bigClassId = returnedData.data.entries[0].id;
                    // 构建大类对象
                    returnedData.data.entries.forEach(function(val){
                        this[val.id] = val;
                    }, vm.data.bigClass);
                }
            }).catch(function(error){
                console.error(error);
            });
        };

        // 获取小类
        vm.getClassMiniType = function(){
            var data = vm.data;
            var queryConfig = {
                funcName: 'getClassMiniType',
                propChain: [],
                showLoadLayer: false,
                urlPlaceholder: {
                    id: data.classId
                }
            };

            TeacherService.getClassMiniType(queryConfig).then(function(returnedData){
                if(returnedData.success){
                    var tempTimePoint = {};
                    var bindTimeItemsData = data.bindTimeItemsData;

                    data.formData.name = returnedData.data.name;
                    data.tempSmallClass.name = returnedData.data.name;
                    data.tempSmallClass.fb_shift_category_id = returnedData.data.fb_shift_category_id;

                    if(returnedData.data.shift_time_slot){
                        returnedData.data.shift_time_slot.forEach(function(val){
                            if(angular.isArray(tempTimePoint[val.day_of_week])){
                                tempTimePoint[val.day_of_week].push(val);
                            }else {
                                tempTimePoint[val.day_of_week] = [val];
                            }
                        });
                    }

                    // 基于开始时间生成指定分钟后的结束时间
                    function baseTimePoint(start, step){
                        var baseDate = new Date('2017/01/01 ' + start);
                        var h = baseDate.getHours();
                        var m = baseDate.getMinutes();
                        var mTotle = step + h * 60 + m;
                        m = mTotle % 60;
                        h = mTotle / 60;
                        baseDate.setHours(h);
                        baseDate.setMinutes(m);
                        h = baseDate.getHours();
                        m = baseDate.getMinutes();
                        h = h > 9 ? h : '0' + h;
                        m = m > 9 ? m : '0' + m;

                        return h + ':' + m;
                    }

                    // 将时间点数组转换成时间段数组
                    function conversionTime(timeArr){
                        var returnArr = [];
                        var valve = true;
                        var temp, data;

                        while(timeArr.length){
                            if(valve){
                                temp = timeArr.splice(0, 1);
                                data = {
                                    type: temp[0].type,
                                    start_time: baseTimePoint(temp[0].time_slot, 0),
                                    end_time: baseTimePoint(temp[0].time_slot, 30)
                                };
                            }

                            valve = true;
                            timeArr.forEach(function(v, i){

                                if(data.type === v.type){
                                    var start = (new Date('2017/01/01 ' + data.start_time)).getTime();
                                    var end = (new Date('2017/01/01 ' + data.end_time)).getTime();
                                    var slot = (new Date('2017/01/01 ' + v.time_slot)).getTime();

                                    if(start === slot){
                                        valve = false;
                                        timeArr.splice(i, 1);
                                    }else if(slot === start - 180000){
                                        valve = false;
                                        data.start_time = baseTimePoint(v.time_slot, 0);
                                        timeArr.splice(i, 1);
                                    }else if(slot === end){
                                        valve = false;
                                        data.end_time = baseTimePoint(v.time_slot, 30);
                                        timeArr.splice(i, 1);
                                    }
                                }
                            });
                            if(valve || timeArr.length === 0){
                                returnArr.push(data);
                            }
                        }

                        return returnArr;
                    }

                    for(var i = 0; i <= 6; i++){
                        if(tempTimePoint[i]){
                            if(tempTimePoint[i].length === 1){
                                bindTimeItemsData.push({
                                    day_of_week: i,
                                    shift_time_slot: [{
                                        type: tempTimePoint[i][0].type,
                                        start_time: baseTimePoint(tempTimePoint[i][0].time_slot, 0),
                                        end_time: baseTimePoint(tempTimePoint[i][0].time_slot, 30)
                                    }]
                                });
                            }else {
                                bindTimeItemsData.push({
                                    day_of_week: i,
                                    shift_time_slot: conversionTime(tempTimePoint[i])
                                });
                            }
                        }else {
                            bindTimeItemsData.push({
                                day_of_week: i,
                                shift_time_slot: []
                            });
                        }
                    }
                }
            }).catch(function(error){
                console.error(error);
            });
        };

        // 添加班型小类
        vm.addClassMiniType = function(){
            var data = vm.data;
            var postConfig = {
                funcName: 'addClassMiniType',
                successMsg: '班型小类添加成功',
                errorMsg: '班型小类添加失败',
                showLoadLayer: false,
                httpPostData: {
                    name: data.formData.name,
                    fb_shift_category_id: data.formData.bigClassId
                }
            };

            TeacherService.addClassMiniType(postConfig).then(function(returnedData){
                var shiftTypeId;
                if(returnedData.success){
                    shiftTypeId = returnedData.data.id;
                    data.classId = shiftTypeId;
                    data.isCheck = false;
                    vm.addShiftTimeSlot(shiftTypeId);
                }
            }).catch(function(error){
                console.error(error);
            });
        };

        // 添加班型连续时段
        vm.addShiftTimeSlot = function(id){
            var postConfig = {
                funcName: 'addShiftTimeSlot',
                successMsg: '班型小类时间段添加成功',
                errorMsg: '班型小类时间段添加失败',
                showLoadLayer: false,
                httpPostData: {
                    data: vm.data.timeItemsData,
                    fb_shift_type_id: id
                }
            };

            TeacherService.addShiftTimeSlot(postConfig).catch(function(error){
                console.error(error);
            });
        };

        vm.updateClassMiniType = function(){
            var data = vm.data;
            var putConfig = {
                funcName: 'updateClassMiniType',
                successMsg: '班型小类修改成功',
                errorMsg: '班型小类修改失败',
                httpPutData: {
                    name: data.formData.name,
                    fb_shift_category_id: data.formData.bigClassId
                },
                urlPlaceholder: {
                    id: data.classId
                }
            };

            TeacherService.updateClassMiniType(putConfig).then(function(returnedData){
                if(returnedData.success){
                    vm.updateShiftTimeSlot();
                }
            }).catch(function(error){
                console.error(error);
            });
        };

        vm.updateShiftTimeSlot = function(){
            var data = vm.data;
            var putConfig = {
                funcName: 'updateShiftTimeSlot',
                successMsg: '班型小类时间段修改成功',
                errorMsg: '班型小类时间段修改失败',
                showLoadLayer: false,
                httpPutData: {
                    data: data.timeItemsData,
                    fb_shift_type_id: data.classId
                },
                urlPlaceholder: {
                    shift_time_id: data.classId
                }
            };

            TeacherService.updateShiftTimeSlot(putConfig).catch(function(error){
                console.error(error);
            });
        };

        vm.deleteMiniType = function(){
            var deleteConfig = {
                funcName: 'deleteMiniType',
                successMsg: '删除成功',
                errorMsg: '删除失败',
                showLoadLayer: false,
                urlPlaceholder: {
                    id: vm.data.classId
                }
            };

            var layerIndex = layer.confirm('确定要删除?', {
                btn: ['确定','取消']
            }, function(){
                layer.close(layerIndex);
                TeacherService.deleteMiniType(deleteConfig).then(function(){
                    $state.go('teacher-class-mini-type');
                }).catch(function(error){
                    console.error(error);
                });
            });
        };

        valiFrom.extenUniqueVali('uniqueShiftType');
        $('#add-small-class-form').form({
            fields: {
                class_number: {
                    rules: [{
                        type: 'empty',
                        prompt: '请输入小类编号(必填项)'
                    },{
                        type: 'uniqueShiftType',
                        prompt: '已存在该小类编号，请确保小类编号的唯一性'
                    }]
                },
                big_class: {
                    rules: [{
                        type: 'empty',
                        prompt: '请选择大类(必填项)'
                    }]
                }
            },
            onSuccess: function(){
                vm.getSmallClassData();
                if(vm.data.classId){
                    var tempSmallClass = vm.data.tempSmallClass;
                    var formData = vm.data.formData;
                    if(tempSmallClass.name !== formData.name || tempSmallClass.fb_shift_category_id != formData.bigClassId ){
                        vm.updateClassMiniType();
                    }else {
                        vm.updateShiftTimeSlot();
                    }
                }else {
                    vm.addClassMiniType();
                }
                return false;
            }
        });
    }
}());
